package com.lyl.module.api.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dtflys.forest.Forest;
import com.lyl.module.api.client.LoginApiClient;
import com.lyl.module.constant.ALIYUN_GLOBAL_VARIABLE;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author Mr.Luo
 * @date 2022-07-21 10:05
 * @desc 登录apiService
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginApiService {
    private final LoginApiClient loginApiClient;

    /**
     * 获取登录二维码
     *
     * @return JSONObject
     */
    public String getLoginQrCode() {
        JSONObject loginQrCode = loginApiClient.getLoginQrCode();
        if (Boolean.FALSE.equals(loginQrCode.getBool("success"))) {
            log.error("获取登录二维码异常, 接口响应体：[{}]", loginQrCode);
            throw new RuntimeException("获取登录二维码异常" + loginQrCode);
        }
        JSONObject jsonObject = loginQrCode.getJSONObject("content").getJSONObject("data");
        //设置全局变量
        ALIYUN_GLOBAL_VARIABLE.T = jsonObject.getStr("t");
        ALIYUN_GLOBAL_VARIABLE.CK = jsonObject.getStr("ck");
        Forest.config().setVariableValue("t", ALIYUN_GLOBAL_VARIABLE.T)
                .setVariableValue("ck", ALIYUN_GLOBAL_VARIABLE.CK);
        return jsonObject.getStr("codeContent");
    }

    /**
     * 检查登录二维码的状态
     *
     * @return JSONObject
     */
    public JSONObject checkQrCodeState() {
        JSONObject checkQrCodeState = loginApiClient.checkQrCodeState();
        checkQrCodeState = checkQrCodeState.getJSONObject("content").getJSONObject("data");
        switch (checkQrCodeState.getStr("qrCodeStatus")) {
            case "NEW":
                //未扫码
                break;
            case "CONFIRMED":
                //扫码成功
                //获取access_token
                String response = Base64.decodeStr(checkQrCodeState.getStr("bizExt"), CharsetUtil.CHARSET_GBK);
                JSONObject result = JSONUtil.parseObj(response).getJSONObject("pds_login_result");
                ALIYUN_GLOBAL_VARIABLE.ACCESS_TOKEN = result.getStr("accessToken");
                Forest.config().setVariableValue("token", ALIYUN_GLOBAL_VARIABLE.ACCESS_TOKEN);
                //获取真正的token
                JSONObject jsonObject = loginApiClient.tokenLogin();
                String code = jsonObject.getStr("goto");
                code = CharSequenceUtil.subBetween(URLUtil.decode(code), "code=", "&");
                jsonObject = getToken(code);
                ALIYUN_GLOBAL_VARIABLE.DRIVE_ID = jsonObject.getStr("default_drive_id");
                ALIYUN_GLOBAL_VARIABLE.ACCESS_TOKEN = jsonObject.getStr("access_token");
                ALIYUN_GLOBAL_VARIABLE.TOKEN_TYPE = jsonObject.getStr("token_type");
                ALIYUN_GLOBAL_VARIABLE.REFRESH_TOKEN = jsonObject.getStr("refresh_token");
                ALIYUN_GLOBAL_VARIABLE.AUTHORIZATION = ALIYUN_GLOBAL_VARIABLE.getAuthorization();
                Forest.config().setVariableValue("authorization",ALIYUN_GLOBAL_VARIABLE.AUTHORIZATION)
                        .setVariableValue("refresh_token",ALIYUN_GLOBAL_VARIABLE.REFRESH_TOKEN);
                return jsonObject;
            default:
                break;
        }
        return checkQrCodeState;
    }

    /**
     * 刷新token
     */
    public synchronized void refreshToken(){
        JSONObject jsonObject = loginApiClient.refreshToken();
        //ALIYUN_GLOBAL_VARIABLE.DRIVE_ID = jsonObject.getStr("default_drive_id");
        ALIYUN_GLOBAL_VARIABLE.ACCESS_TOKEN = jsonObject.getStr("access_token");
        ALIYUN_GLOBAL_VARIABLE.TOKEN_TYPE = jsonObject.getStr("token_type");
        ALIYUN_GLOBAL_VARIABLE.REFRESH_TOKEN = jsonObject.getStr("refresh_token");
        ALIYUN_GLOBAL_VARIABLE.AUTHORIZATION = ALIYUN_GLOBAL_VARIABLE.getAuthorization();
        ALIYUN_GLOBAL_VARIABLE.setDriveId(jsonObject.getStr("default_drive_id"));
        ALIYUN_GLOBAL_VARIABLE.setNextRefreshTokenTime();
        Forest.config().setVariableValue("authorization",ALIYUN_GLOBAL_VARIABLE.AUTHORIZATION)
                .setVariableValue("refresh_token",ALIYUN_GLOBAL_VARIABLE.REFRESH_TOKEN)
                .setVariableValue("drive_id",ALIYUN_GLOBAL_VARIABLE.DRIVE_ID);
    }

    private JSONObject getToken(String code){
        return loginApiClient.getToken(code,"normal", ALIYUN_GLOBAL_VARIABLE.CLIENT_ID);
    }
}
